package initialize

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
	"log"
	"os"
	"pm_back_server/user-server/global"
	"pm_back_server/user-server/model"
	"time"
)

func InitDB() {
	config := global.ServerConfig

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
		config.MysqlInfo.User,
		config.MysqlInfo.Password,
		config.MysqlInfo.Host,
		config.MysqlInfo.Port,
		config.MysqlInfo.Name)

	newLogger := logger.New(log.New(os.Stdout, "\r\n", log.LstdFlags), logger.Config{
		SlowThreshold: time.Second,
		LogLevel:      logger.Info,
		Colorful:      true,
	})

	var err error
	global.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true,
		},
	})
	if err != nil {
		panic(fmt.Sprintf("connect db faily, error: %s", err.Error()))
	} else {
		fmt.Println("connect db successfully")
	}

	_ = global.DB.AutoMigrate(&model.User{})
}
